import styles from '@/components/common/PateoTable/TableList.less';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Cascader,
  Checkbox,
  Col,
  DatePicker,
  Descriptions,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Radio,
  Row,
  Select,
  Space,
  Spin,
  Upload,
} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { createRef, PureComponent } from 'react';
import { Map } from 'react-amap';
import router from 'umi/router';
import * as XLSX from 'xlsx';
import { fenceUserTypeHash, repositoryHash } from '.';
const { Option } = Select;
import { downloadFileByUrl } from '@/utils/utils';
@connect(state => ({
  baseUser: state.baseUser,
}))
export default class CustomizeAdd extends PureComponent {
  state = {
    fenceUserType: null,
    canDraw: true,
    operateType: 0,
    currentEditor: null,
    effectType: 0, // 0: 无限制, 1: 有限制
    originData: '',
    orgData: [],
    dealerData: [],
    detail: {},
    loading: false,
    saveloading: false,
    orgFilterData: [],

    imports: [],
    errorImports: [],
    uploadVisible: false,
    importLoading: false,
    templateFileUrl: '',
    workbook: null,
    dealerOptions: [],
    currentOrgSid: null,
  };

  areaStyle = {
    fillOpacity: 0.7,
    fillColor: '#4B9248',
    strokeStyle: 'solid',
    strokeColor: '#006633',
  };

  formRef = createRef();

  resolve;
  mapPromise = new Promise(resolve => (this.resolve = resolve));

  fenceId;
  isDetail = false;
  UNSAFE_componentWillMount() {
    this.fenceId = this.props.location.query.fenceId;
    this.isDetail = !!this.props.location.query.isDetail;
    console.log(this.fenceId);
    // const { dispatch } = this.props;
    // dispatch({
    //   type: 'basedata/fetchDealerByLogin',
    //   callback: response => {
    //     // if (response.statusCode === '0') {
    //     this.setState({
    //       dealerOptions: response.data
    //         ?.filter(item => item.code !== '')
    //         .map(d => {
    //           //  需求迭代20231211：显示内容为“经销商名称(经销商编码)”
    //           const name =`${d.name}(${d.code})`;
    //           return (
    //             <Option title={name} key={d.code}>
    //               {name}
    //             </Option>
    //           );
    //     }),
    //     });
    //     // } else {
    //     //   message.error(response.statusMessage);
    //     // }
    //   },
    // });
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'electricFenceMng/getData',
      payload: { url: '/common/template/detail', templateCode: 'circleFenceImport' },
      callback: res => {
        this.setState({ templateFileUrl: res.data ? res.data.templateUrl : null });
      },
    });
    return this.init();
  }

  /**
   * 根据组织id获取经销商数据
   * @param {*} orgId
   */
  fetchDealerData = orgId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/getDataWithRes',
      payload: { url: '/mscreditbusiness/merchant/getDealers', orgId },
      callback: response => {
        // if (response.statusCode === '0') {
        this.setState({
          dealerOptions: response.data
            ?.filter(item => item.code !== '')
            .map(d => {
              const name = `${d.name}(${d.code})`;
              return (
                <Option title={name} key={d.code}>
                  {name}
                </Option>
              );
            }),
        });
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };
  dealTreeData = (orgParent, list) => {
    const arr =
      list
        .map(e => ({
          orgParent: e.orgParent,
          sid: e.sid,
          value: e.orgCode,
          label: e.orgName,
        }))
        .filter(c => c.orgParent === orgParent) || [];
    arr.forEach(item => {
      const children = this.dealTreeData(item.sid, list);
      if (children.length) {
        item.children = children;
      }
    });
    return arr;
  };

  initOrgData = async () => {
    const res = await this.props.dispatch({
      type: 'http/getData',
      payload: {
        url: '/org/findorglistbytoken',
      },
    });
    if (res.statusCode === '0' && res.data && res.data.length) {
      const originData = JSON.stringify(res.data);
      const orgData = JSON.parse(originData);
      this.setState({
        originData,
        orgData: this.dealTreeData(orgData[0].orgParent, orgData),
      });
    }

    // 获取经销商（调接口查询真实经销商数据）
    // let filterData = [];
    // const orgData = JSON.parse(this.state.originData);
    // filterData = orgData.map((item) => {
    //   return item.orgCode;
    // });
    // this.props.dispatch({
    //   type: 'http/postListList',
    //   payload: { url: '/commodity/vehicle/filter/dealercodes', list: filterData },
    //   callback: (res) => {
    //     if (res.statusCode === '0') {
    //       this.setState({
    //         orgFilterData: res.data,
    //       });
    //     }
    //   },
    // });
  };

  // 获取多边形中点
  getCenterPoint = data => {
    let lng = 0.0,
      lat = 0.0;
    for (let i = 0; i < data.length; i++) {
      lng = lng + parseFloat(data[i]['lng']);
      lat = lat + parseFloat(data[i]['lat']);
    }
    lng = lng / data.length;
    lat = lat / data.length;
    return { lng: Number(lng.toFixed(6)), lat: Number(lat.toFixed(6)) };
  };

  transformAddress = async latlng => {
    const { geocoder } = await this.mapPromise;
    return new Promise(resolve => {
      geocoder.getAddress([latlng.lng, latlng.lat], (status, result) => {
        if (status === 'complete' && result.regeocode && result.regeocode.formattedAddress) {
          resolve(result.regeocode.formattedAddress);
        } else {
          resolve('');
        }
      });
    });
  };

  areaBindClick = (e, ins, tool) => {
    if (this.fenceId) {
      // 编辑只能创建 1 个
      this.setState({ canDraw: false });
      tool.close();
    }
    e.obj.on('click', () => {
      this.currentObj = e.obj;
      // 点击图形前, 临死关闭可画图状态
      tool.close();
      if (this.state.currentEditor) {
        this.state.currentEditor.close();
      }
      const currentEditor =
        e.obj.CLASS_NAME === 'AMap.Circle'
          ? new window.AMap.CircleEditor(ins, e.obj)
          : new window.AMap.PolyEditor(ins, e.obj);
      currentEditor.open();
      this.setState({ currentEditor });
      // 开始编辑后, 重新可以画图
      if (this.state.canDraw) {
        this.typeSwitch(this.state.operateType);
      }
    });
  };

  currentObj;
  init = async () => {
    this.setState({ loading: true });

    // 地图初始化
    const { ins, tool } = await this.mapPromise;
    tool.on('draw', e => this.areaBindClick(e, ins, tool));

    // 位置输入后自动跳转到指定位置
    new AMap.Autocomplete({ input: 'autoinput' }).on('select', val => {
      ins.remove(ins.getAllOverlays('marker'));
      if (!val.poi.location) {
        ins.setCity(val.poi.name);
      } else {
        console.log('val.poi.location.lat.lat', val.poi.location.lat.lat);
        var marker = new AMap.Marker({
          position: [val.poi.location.lng, val.poi.location.lat], // 基点位置
          offset: new AMap.Pixel(-26, -13), // 设置点标记偏移量
          anchor: 'bottom-left', // 设置锚点方位
        });
        ins.add(marker);
        ins.setCenter(val.poi.location);
      }
    });

    // 地图初始化完成以后, 在做详情数据拉取
    if (!this.fenceId) {
      // 不 awiat
      this.initOrgData();
      this.setState({ loading: false });
      return;
    }
    const res = await this.props.dispatch({
      type: 'http/getData',
      payload: {
        url: '/electricfence/getfencedetail',
        fenceId: this.fenceId,
      },
    });

    if (res.statusCode === '0') {
      const data = res.data;
      const fields = {
        warningConfigs: res.data.warningConfigs,
      };
      if (data.warningBeginDate && data.warningEndDate) {
        fields.effectType = 1;
        fields.fenceExpireDate = [moment(data.warningBeginDate), moment(data.warningEndDate)];
      } else {
        fields.effectType = 0;
      }
      console.log(fields);
      this.formRef.current.setFieldsValue({
        ...fields,
        dealerCode: res.data.dealerCode,
        repository: res.data.repository,
      });
      this.setState({ detail: res.data, effectType: fields.effectType });

      // 地图回显 - 圆
      if (data.circleList) {
        data.circleList.forEach(e => {
          const circle = {
            obj: new AMap.Circle({
              map: ins,
              ...this.areaStyle,
              radius: e.radius,
              center: [e.centerLng, e.centerLat],
            }),
          };
          this.areaBindClick(circle, ins, tool);
        });
        this.setState({ operateType: 1 });
      }

      // 地图回显 - 多边形
      if (data.polygonList) {
        data.polygonList.forEach(e => {
          const polygon = {
            obj: new AMap.Polygon({
              map: ins,
              ...this.areaStyle,
              path: e.pointInfos.map(item => new AMap.LngLat(item.lng, item.lat)),
              // draggable: true,
            }),
          };
          this.areaBindClick(polygon, ins, tool);
        });
        this.setState({ operateType: 2 });
      }

      ins.setFitView();
    }

    this.setState({ loading: false });
  };

  importCircleDraw = async () => {
    const { ins, tool } = await this.mapPromise;
    this.state.imports.forEach(e => {
      const circle = {
        obj: new AMap.Circle({
          map: ins,
          ...this.areaStyle,
          radius: e.radius,
          center: [e.centerLng, e.centerLat],
        }),
      };
      this.areaBindClick(circle, ins, tool);
    });
    ins.setFitView();
    this.setState({ uploadVisible: false, imports: [], errorImports: [] });
  };

  importCircle = async file => {
    if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      message.warning('请上传xlsx格式文件');
      return false;
    }
    if (file.size / 1024 / 1024 > 10) {
      message.warning('文件大小不能大于10MB');
      return false;
    }

    this.setState({ importLoading: true });
    let errorImports = [];
    const self = this;
    const imports = await new Promise(resolve => {
      const reader = new FileReader();
      reader.onload = function (e) {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        self.setState({ workbook: workbook });
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        let res = XLSX.utils.sheet_to_json(worksheet, { header: 1 }).slice(1);
        // 0-经度, 1-纬度, 2-半径
        res = res || [];
        const imports = [];
        for (let i = 0; i < res.length; i++) {
          let e = res[i];
          e = e || [];
          if (!e.join('')) {
            // 过滤全部为空行的情况
            continue;
          }
          const centerLng = e[0];
          const centerLat = e[1];
          const radius = e[2];
          let isError = false;
          let errorStrArr = [];
          if (!centerLng) {
            isError = true;
            errorStrArr.push('经度不能为空');
          }
          if (parseFloat(centerLng) < -180 || parseFloat(centerLng) > 180) {
            isError = true;
            errorStrArr.push('经度为不合理值');
          }
          if (!centerLat) {
            isError = true;
            errorStrArr.push('纬度不能为空');
          }
          if (parseFloat(centerLat) < -90 || parseFloat(centerLat) > 90) {
            isError = true;
            errorStrArr.push('纬度为不合理值');
          }
          if (!radius) {
            isError = true;
            errorStrArr.push('半径不能为空');
          }
          if (parseFloat(radius) < 0) {
            isError = true;
            errorStrArr.push('半径不能为负数');
          }
          imports.map(e => {
            if (e.centerLng === centerLng && e.centerLat === centerLat && e.radius === radius) {
              isError = true;
              errorStrArr.push('重复数据');
            }
          });
          if (isError) {
            let errorStr = errorStrArr.join('、');
            XLSX.utils.sheet_add_aoa(worksheet, [[errorStr]], { origin: `D${i + 2}` });
            errorImports.push(i);
          } else {
            imports.push({
              centerLng,
              centerLat,
              radius,
            });
          }
        }
        resolve(imports);
      };
      reader.readAsArrayBuffer(file);
    })
      .catch(e => {})
      .finally(() => {
        this.setState({ importLoading: false });
      });

    this.setState({ imports: imports || [] });
    this.setState({ errorImports: errorImports || [] });
    return false;
  };

  delete = async () => {
    const { ins } = await this.mapPromise;
    this.state.currentEditor.close();
    ins.remove(this.currentObj);
    if (this.fenceId) {
      this.setState({ canDraw: true });
    }
    this.setState({ currentEditor: null });
    this.typeSwitch(this.state.operateType);
  };

  typeSwitch = async operateType => {
    this.setState({ operateType });
    const { tool } = await this.mapPromise;
    switch (operateType) {
      case 1:
        // 可以开始画圆
        tool.circle(this.areaStyle);
        break;
      case 2:
        // 可以开始画多边形
        tool.polygon(this.areaStyle);
        break;
      default:
        tool.close();
    }
  };

  onEffectTypeChange = e => {
    this.setState({ effectType: e.target.value });
    this.formRef.current.setFieldsValue({
      fenceExpireDate: [],
    });
  };

  close = () => {
    router.replace(`${self === top ? '' : '/external'}/electricFence/electricFenceMng`);
  };

  handleSubmit = () => {
    this.formRef.current.submit();
  };

  onFinish = async args => {
    this.setState({ saveloading: true });

    const { ins } = await this.mapPromise;
    const circleList = [];
    let list = ins.getAllOverlays('circle');
    for (let i = 0; i < list.length; i++) {
      const latlng = list[i].getCenter();
      const radius = list[i].getRadius();
      if (radius < 1) {
        message.error('电子围栏半径不能小于1米');
        this.setState({ saveloading: false });
        return;
      }
      const fenceCenterAddress = await this.transformAddress(latlng);
      circleList.push({
        lat: latlng.lat,
        lng: latlng.lng,
        centerLat: latlng.lat,
        centerLng: latlng.lng,
        fenceCenterAddress,
        radius,
      });
    }
    const polygonList = [];
    list = ins.getAllOverlays('polygon');
    for (let i = 0; i < list.length; i++) {
      const pointInfos = list[i].getPath().map(e => ({ lat: e.lat, lng: e.lng }));
      const latlng = this.getCenterPoint(pointInfos);
      const fenceCenterAddress = await this.transformAddress(latlng);
      polygonList.push({
        centerLat: latlng.lat,
        centerLng: latlng.lng,
        fenceCenterAddress,
        pointInfos,
      });
    }

    const post = {
      id: this.fenceId,
      fenceType: 0,
      fenceUserType: this.fenceId ? this.state.detail.fenceUserType : args.fenceUserType,
      repository: this.fenceId ? this.state.detail.repository : args.repository,
      warningBeginDate:
        this.state.effectType === 0
          ? undefined
          : args.fenceExpireDate
          ? args.fenceExpireDate[0].format('YYYY-MM-DD')
          : undefined,
      warningEndDate:
        this.state.effectType === 0
          ? undefined
          : args.fenceExpireDate
          ? args.fenceExpireDate[1].format('YYYY-MM-DD')
          : undefined,
      warningConfigs: args.warningConfigs,
      orgCode: this.fenceId
        ? this.state.detail.orgCode
        : args.orgCode && args.orgCode.length
        ? args.orgCode[args.orgCode.length - 1]
        : undefined,
      orgId: this.fenceId ? this.state.detail.orgId : this.state.currentOrgSid,
      dealerCode: this.fenceId ? this.state.detail.dealerCode : args.dealerCode,
      polygonList,
      circleList,
    };

    if (!post.polygonList.length && !post.circleList.length) {
      message.error('请至少绘制1个围栏');
      this.setState({ saveloading: false });
      return;
    }

    if (this.fenceId) {
      // 编辑的时候, 要传图形类型
      if (post.polygonList.length + post.circleList.length > 1) {
        message.error('只能保存一个围栏区域');
        this.setState({ saveloading: false });
        return;
      }
      post.fenceShapeType = post.polygonList.length ? 2 : 1;
      post.id = this.fenceId;
    }

    const res = await this.props.dispatch({
      type: 'http/postObj',
      payload: {
        url: !this.fenceId ? '/electricfence/savefence' : '/electricfence/updateFence',
        ...post,
      },
    });
    await this.setState({ saveloading: false });
    if (res.statusCode === '0') {
      message.success('保存成功');
      router.replace(`${self === top ? '' : '/external'}/electricFence/electricFenceMng`);
    }
  };

  render() {
    const { dealerOptions, templateFileUrl } = this.state;
    return (
      <Card
        title={!this.isDetail ? (this.fenceId ? '编辑围栏' : '新增围栏') : '围栏详情'}
        onClose={this.close}
        bodyStyle={{ padding: '12px 24px' }}
        width={800}
        extra={
          <Space>
            <Button size="small" onClick={this.close}>
              取消
            </Button>
            {!this.isDetail ? (
              <Button
                size="small"
                onClick={this.handleSubmit}
                type="primary"
                loading={this.state.saveloading}
              >
                保存
              </Button>
            ) : (
              ''
            )}
          </Space>
        }
      >
        <Spin spinning={this.state.loading}>
          <Form onFinish={this.onFinish} ref={this.formRef}>
            {this.fenceId ? (
              <>
                <Row>
                  <Col lg={12} md={12} sm={24} xs={24}>
                    <Form.Item label="围栏编号">{this.state.detail.fenceCode}</Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col lg={12} md={12} sm={24} xs={24}>
                    <Form.Item label="围栏名称">{this.state.detail.fenceName}</Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col lg={12} md={12} sm={24} xs={24}>
                    <Form.Item label="围栏类型">
                      {fenceUserTypeHash[this.state.detail.fenceUserType]}
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col lg={12} md={12} sm={24} xs={24}>
                    <Form.Item label="围栏所属组织">{this.state.detail.orgName}</Form.Item>
                  </Col>
                </Row>
                {this.state.detail?.fenceUserType === '1' && (
                  <>
                    <Row>
                      <Col lg={12} md={12} sm={24} xs={24}>
                        <Form.Item label="所属经销商">
                          {this.state.detail.dealerName +
                            (this.state.detail.dealerCode
                              ? '(' + this.state.detail.dealerCode + ')'
                              : '')}
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row>
                      <Col lg={12} md={12} sm={24} xs={24}>
                        <Form.Item label="所属仓库">
                          {repositoryHash[this.state.detail.repository] || ''}
                        </Form.Item>
                      </Col>
                    </Row>
                  </>
                )}
                {/* {this.state.detail.dealerName !== null &&
                this.state.detail.dealerName !== undefined &&
                this.state.detail.dealerName.length > 0 ? (
                  <Row>
                    <Col lg={12} md={12} sm={24} xs={24}>
                      <Form.Item label="经销商">{this.state.detail.dealerName}</Form.Item>
                    </Col>
                  </Row>
                ) : null} */}
              </>
            ) : (
              <>
                <Row>
                  <Col span={8}>
                    <Form.Item
                      label="围栏类型"
                      name="fenceUserType"
                      rules={[{ required: true, message: '请选择围栏类型' }]}
                    >
                      <Select
                        disabled={this.isDetail}
                        placeholder="请选择围栏类型"
                        allowClear={false}
                        onChange={e => {
                          this.setState({ fenceUserType: e });
                        }}
                      >
                        <Option key="0">非经销商</Option>
                        <Option key="1">经销商</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={1} />
                </Row>

                <Row>
                  <Col span={8}>
                    <Form.Item
                      label="所属组织"
                      name="orgCode"
                      rules={[{ required: true, message: '请选择所属组织' }]}
                    >
                      <Cascader
                        changeOnSelect
                        allowClear={false}
                        options={this.state.orgData}
                        placeholder="请选择所属组织"
                        showSearch
                        onChange={e => {
                          // this.setState({ dealerData: [] });
                          this.setState({ currentOrgSid: null, dealerOptions: [] });
                          this.formRef.current.resetFields(['dealerCode']);
                          if (!e) {
                            return;
                          }

                          const code = e[e.length - 1];
                          let orgData = JSON.parse(this.state.originData);
                          const current = orgData.find(e => e.orgCode === code);
                          // console.log(current);
                          this.setState({ currentOrgSid: current.sid });
                          if (current.sid) {
                            this.fetchDealerData(current.sid);
                          }
                          // const changeData = orgData.filter(
                          //   e => e.orgLevelCode.indexOf(current.orgLevelCode + '-') >= 0,
                          // );
                          // orgData = orgData.filter((e) => e.orgType === 2);
                          // if (!current) {
                          //   return;
                          // }

                          // if (current.orgType === 3) {
                          //   // todo: 如果是授信机构, 是另外的逻辑, 待实现
                          //   return;
                          // }

                          // if (this.state.orgFilterData.indexOf(current.orgCode) > -1) {
                          //   this.setState({
                          //     // dealerData: [
                          //     //   {
                          //     //     label: current.orgName,
                          //     //     value: current.orgCode,
                          //     //     children: this.dealTreeData(
                          //     //       current.sid,
                          //     //       changeData.filter(
                          //     //         e =>
                          //     //           [2].indexOf(e.orgType) > -1 &&
                          //     //           this.state.orgFilterData.indexOf(e.orgCode) > -1,
                          //     //       ),
                          //     //     ),
                          //     //   },
                          //     // ],
                          //     dealerData: this.dealTreeData(
                          //       current.sid,
                          //       orgData.filter(
                          //         (e) => this.state.orgFilterData.indexOf(e.orgCode) > -1,
                          //       ),
                          //     ),
                          //   });
                          // } else {
                          //   this.setState({
                          //     // dealerData: this.dealTreeData(
                          //     //   current.sid,
                          //     //   changeData.filter(
                          //     //     e =>
                          //     //       [2].indexOf(e.orgType) > -1 &&
                          //     //       this.state.orgFilterData.indexOf(e.orgCode) > -1,
                          //     //   ),
                          //     // ),
                          //     dealerData: this.dealTreeData(
                          //       current.sid,
                          //       orgData.filter(
                          //         (e) => this.state.orgFilterData.indexOf(e.orgCode) > -1,
                          //       ),
                          //     ),
                          //   });
                          // }
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={1} />
                  {/* <Col span={5}>
                  <Form.Item label="经销商" name="dealerCode">
                    <Cascader
                      changeOnSelect
                      options={this.state.dealerData}
                      placeholder="请选择经销商"
                    />
                  </Form.Item>
                </Col> */}
                </Row>
                {this.state.fenceUserType === '1' || this.state.detail?.fenceUserType === '1' ? (
                  // 经销商
                  <>
                    <Row>
                      <Col span={8}>
                        <Form.Item
                          label="所属经销商"
                          name="dealerCode"
                          rules={[{ required: true, message: '请选择所属经销商' }]}
                        >
                          <Select
                            disabled={this.isDetail}
                            allowClear={false}
                            placeholder="请选择所属经销商"
                            showSearch
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            optionFilterProp="children"
                          >
                            {dealerOptions}
                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={8}>
                        <Form.Item label="所属仓库" name="repository">
                          <Select placeholder="请选择所属仓库" allowClear disabled={this.isDetail}>
                            <Option key="0">主库</Option>
                            <Option key="1">二库</Option>
                            <Option key="2">二网</Option>
                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                  </>
                ) : null}
              </>
            )}

            {/* <Row>
              <Col>
                <Form.Item
                  label="围栏预警方式"
                  name="warningConfigs"
                  rules={[{ required: true, message: '请选择围栏预警方式' }]}
                >
                  <Checkbox.Group
                    options={[
                      { label: '进入围栏', value: 1 },
                      { label: '离开围栏', value: 2 },
                      { label: '围栏内', value: 3 },
                      { label: '围栏外', value: 4 },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row> */}
            <Row>
              <Col>
                <Form.Item
                  label="围栏有效期"
                  name="effectType"
                  rules={[{ required: true, message: '请选择围栏有效期' }]}
                  initialValue={0}
                >
                  <Radio.Group
                    disabled={this.isDetail}
                    onChange={this.onEffectTypeChange}
                    options={[
                      { label: '无限制', value: 0 },
                      { label: '限制', value: 1 },
                    ]}
                    value={this.state.effectType}
                  />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  name="fenceExpireDate"
                  rules={[{ required: !!this.state.effectType, message: '请选择限制日期' }]}
                >
                  <DatePicker.RangePicker
                    disabled={this.isDetail || !this.state.effectType}
                    style={{ width: '100%' }}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col>
                <Form.Item label="" initialValue={4}>
                  <Radio.Group
                    disabled={!this.state.canDraw || this.isDetail}
                    options={[
                      { label: '画圆', value: 1 },
                      { label: '画多边形', value: 2 },
                      !this.fenceId ? { label: '取消画图', value: 0 } : null,
                    ].filter(Boolean)}
                    onChange={e => {
                      console.log(e);
                      return this.typeSwitch(e.target.value);
                    }}
                    value={this.state.operateType}
                  />
                </Form.Item>
              </Col>
              {/* {this.fenceId ? null : (
                <Col>
                  <Form.Item>
                    <Button type="primary" onClick={() => this.setState({ uploadVisible: true })}>
                      批量上传围栏区域
                    </Button>
                  </Form.Item>
                </Col>
              )} */}
            </Row>
          </Form>
          <div
            style={{
              // height: 'calc(100vh - 420px)',
              border: '1px solid #d9d9d9',
              position: 'relative',
            }}
          >
            <Input
              id="autoinput"
              style={{
                position: 'absolute',
                left: '10px',
                bottom: '25px',
                width: '270px',
                zIndex: 1,
              }}
            />
            {!this.isDetail && this.state.currentEditor ? (
              <Popconfirm title="确定清除当前选中围栏？" placement="left" onConfirm={this.delete}>
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  size="small"
                  style={{ position: 'absolute', right: '10px', top: '10px', zIndex: 1 }}
                >
                  删除
                </Button>
              </Popconfirm>
            ) : null}
            <div style={{ height: 485, minHeight: 'calc(100vh - 420px)' }}>
              <Map
                ak={'19dbf6ffd63917bac5a923432ed8ca7a'}
                events={{
                  created: async ins => {
                    await Promise.all([
                      new Promise(resolve => window.AMap.plugin('AMap.MouseTool', resolve)),
                      new Promise(resolve => window.AMap.plugin('AMap.CircleEditor', resolve)),
                      new Promise(resolve => window.AMap.plugin('AMap.PolyEditor', resolve)),
                      new Promise(resolve => window.AMap.plugin('AMap.Geocoder', resolve)),
                      new Promise(resolve => window.AMap.plugin('AMap.Autocomplete', resolve)),
                    ]);
                    this.resolve({
                      ins,
                      tool: new window.AMap.MouseTool(ins),
                      geocoder: new window.AMap.Geocoder({}),
                    });
                  },
                }}
              />
            </div>
          </div>
        </Spin>
        <Modal
          title="批量导入"
          visible={this.state.uploadVisible}
          okButtonProps={{ size: 'small' }}
          cancelButtonProps={{ size: 'small' }}
          onCancel={() => this.setState({ uploadVisible: false, imports: [], errorImports: [] })}
          footer={[
            <Button key="back" type="primary" size="default" onClick={this.importCircleDraw}>
              保存
            </Button>,
          ]}
        >
          <Descriptions column={1} style={{ paddingTop: 10, paddingLeft: 8 }}>
            <Descriptions.Item label="模板">
              {/* {this.state.templateFileUrl ? (
                <a href={this.state.templateFileUrl} title="点击下载模板文件">
                  下载模板文件
                </a>
              ) : (
                '暂无模板文件'
              )} */}
              {templateFileUrl ? (
                <a
                  onClick={() => {
                    downloadFileByUrl(
                      templateFileUrl,
                      `批量导入围栏区域${moment().format('YYYYMMDD')}.xlsx`,
                    );
                  }}
                >
                  点击下载模板文件
                </a>
              ) : (
                '暂无模板文件'
              )}
            </Descriptions.Item>
            <Descriptions.Item label="文件">
              <Upload
                className={styles.uploadFile}
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                // onChange={this.handleFileChange}
                showUploadList={false}
                beforeUpload={this.importCircle}
                loading={this.state.importLoading}
              >
                <Button size="small" icon={<UploadOutlined />} type="primary">
                  导入
                </Button>
              </Upload>
              &nbsp;&nbsp; 成功导入{this.state.imports.length}条
              {this.state.errorImports.length > 0
                ? `    失败导入${this.state.errorImports.length}条`
                : ''}
              {this.state.errorImports.length > 0 ? (
                <div
                  className={styles.downloadErrorFile}
                  onClick={() => {
                    XLSX.writeFile(this.state.workbook, 'm18_Electronic_Fence_Area.xlsx');
                  }}
                >
                  下载结果文件
                </div>
              ) : null}
            </Descriptions.Item>
          </Descriptions>
        </Modal>
      </Card>
    );
  }
}
